package org.kaer.election.ui;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.kaer.election.R;
import org.kaer.election.application.ElectionVoteApplication;
import org.kaer.election.fragment.BaseFragment;
import org.kaer.election.trade.ExampleClient;
import org.kaer.election.utils.ActivityUtils;
import org.kaer.election.utils.ExitAppUtils;
import org.kaer.election.utils.LogUtils;

import fynn.app.ProgressDialog;
import fynn.app.PromptDialog;

public abstract class BaseActivity extends AppCompatActivity implements OnClickListener {
    protected ElectionVoteApplication app = null;
    protected ExampleClient mExampleClient;
    protected Bundle mBundle;
    protected ProgressDialog progressDialog;
    protected LinearLayout commonbgLL;

    protected abstract int getContentViewId();

    protected abstract int getFragmentContentId();

    private IntentFilter filter = new IntentFilter("websocket_closed");

    protected TextView titleTv, titleRightTv;
    protected ImageView titleLeftIv, titleRightIv;
    protected int leftFlag, rightFlag;

    protected final int TITLE_NONE = -1;
    protected final int TITLE_SLIDING = 0;
    protected final int TITLE_SETTING = 1;
    protected final int TITLE_RETURN = 2;
    protected final int TITLE_DELETE = 3;

    public void addFragment(BaseFragment fragment) {
        if (fragment != null) {
            getSupportFragmentManager().beginTransaction().replace(getFragmentContentId(), fragment, fragment.getClass().getSimpleName()).addToBackStack(fragment.getClass().getSimpleName()).commitAllowingStateLoss()
            ;
        }
    }

    public void removeFragment() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            getSupportFragmentManager().popBackStack();
        } else {
            finish();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        ActivityUtils.addActivity(this);
        mExampleClient = ExampleClient.getInstance();
        app = (ElectionVoteApplication) getApplication();
        mBundle = getIntent().getExtras();
        if (mBundle == null)
            mBundle = new Bundle();
        ExitAppUtils.getInstance().addActivity(this);
    }

    /**
     * @param id 标题id
     */
    public void initTitle(int id) {
        initTitle(TITLE_NONE, getResources().getString(id), TITLE_NONE);
    }

    public void initTitle(String title) {
        initTitle(TITLE_NONE, title, TITLE_NONE);
    }

    /**
     * @param leftFlag  是否添加返回
     * @param title     标题
     * @param rightflag 右侧标题类型 -1=没有
     */
    protected void initTitle(int leftFlag, String title, int rightflag) {
        this.leftFlag = leftFlag;
        this.rightFlag = rightflag;
        if (leftFlag != TITLE_NONE) {
            titleLeftIv = (ImageView) findViewById(R.id.title_ivLeft);
            titleLeftIv.setVisibility(View.VISIBLE);
            findViewById(R.id.title_llLeft).setOnClickListener(this);
            if (leftFlag == TITLE_RETURN) {
                titleLeftIv.setImageResource(R.drawable.back);

            }

        }
        titleTv = (TextView) findViewById(R.id.titleTv);
        titleTv.setText(title);
        if (rightflag != TITLE_NONE) {
            findViewById(R.id.title_llRight).setOnClickListener(this);
            if (rightFlag <= 20) {
                titleRightIv = (ImageView) findViewById(R.id.title_ivRight);
                titleRightIv.setVisibility(View.VISIBLE);
                if (rightFlag == TITLE_DELETE) {
                    // titleRightIv.setImageResource(R.drawable.delete);
                } else if (rightFlag == TITLE_SETTING) {
                    //  titleRightIv.setImageResource(R.drawable.setting);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogUtils.i("ElectionActivity.receiveaction " + action);

            if ("websocket_closed".equals(action)) {
                if ("ElectionActivity".equals(context.getClass().getSimpleName())) {
                    LogUtils.i("ElectionActivity.equals(context.getClass().getSimpleName())");

                    ((ElectionActivity) context).finish();
                } else if ("MainActivity".equals(context.getClass().getSimpleName())) {
                    LogUtils.i("getSupportFragmentManager().getBackStackEntryCount()=" + getSupportFragmentManager().getBackStackEntryCount());
                    if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
                        removeFragment();
                    }
                }
            }
        }
    };

    protected void initCommonBg() {
        commonbgLL = (LinearLayout) findViewById(R.id.bgll);
        if (commonbgLL != null) {
            commonbgLL.getBackground().setAlpha(50);
        }
    }

    /**
     * @param cls
     */
    protected void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    /**
     * @param cls
     * @param mBundle
     */
    protected void startActivity(Class<?> cls, Bundle mBundle) {
        try {
            Intent intent = new Intent();
            intent.setClass(this, cls);
            if (mBundle != null) {
                intent.putExtras(mBundle);
            }
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param cls
     * @param requstCode
     * @param mBundle
     */
    protected void startActivityForResult(Class<?> cls, int requstCode, Bundle mBundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (mBundle != null) {
            intent.putExtras(mBundle);

        }
        startActivityForResult(intent, requstCode);

    }

    /**
     * @param cls
     * @param resultCode
     */
    protected void endActivityForResult(Class<?> cls, int resultCode) {
        endActivityForResult(cls, resultCode, null);

    }

    /**
     * @param cls
     * @param resultCode
     * @param mBundle
     */
    protected void endActivityForResult(Class<?> cls, int resultCode, Bundle mBundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (mBundle != null) {
            intent.putExtras(mBundle);

        }
        setResult(resultCode, intent);
        finish();

    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
//                finish();
//                return true;
//            }
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    protected void showProgressDialog(String message, Context context) {
        try {
            dismissDialog();
            progressDialog = new ProgressDialog.Builder(context).setMessage(message).setCancelable(true).create();
            progressDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void showProgressDialog(String message) {

        showProgressDialog(message, BaseActivity.this);
    }

    protected void dismissDialog() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();

    }

    public void showPromptDialog(String message) {
        showPromptDialog(message, new PromptDialog.OnClickListener() {
            @Override
            public void onClick(Dialog dialog, int which) {
                dialog.dismiss();
            }
        });

    }

    public void showPromptDialog(String message, PromptDialog.OnClickListener listener) {
        new PromptDialog.Builder(BaseActivity.this).setViewStyle(PromptDialog.VIEW_STYLE_TITLEBAR_COLOR).setTitleBarColor(getResources().getColor(R.color.colorPrimaryDark)).setTitle("提示").setTitleSize(getResources().getDimension(R.dimen.textsize26)).setMessage(message).setMessageSize(getResources().getDimension(R.dimen.textsize24)).setButton1("确定", listener).setButton1Size(getResources().getDimension(R.dimen.textsize24)).setCancelable(false)
                .create().show();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.title_llLeft:
                onLeftClick();
                break;
            case R.id.title_llRight:
                onRightClick();
                break;

            default:
                break;
        }

    }

    protected void onLeftClick() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            removeFragment();
        } else
            finish();
    }

    protected void onRightClick() {

    }

    protected void setMargins(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

}
